      var customerTransactionGrid,grid;

      $(function(){


              grid=  $("#customerGrid").jqGrid({
                url: "search",
                datatype: "json",
                mtype: "GET",
                colNames: ["Name", "Nick Name", "City","Phone Number","Mobile", "Company", 'Actions'],
                colModel: [
                    { name: "nickName", width: 125 },
                    { name: "name", width: 160 },
                    { name: "address.city", width: 80, align: "left" },
                    { name: "phoneNumber", width: 80, align: "left" },
                    { name: "mobileNumber", width: 80, align: "left" },
                    { name: "companyName", width: 150, align: "left" },
                    { name : 'customerId', index:'customerId', sortable:false,editable:false ,formatter:actionFormat, unformat:actionUnFormat,key:true},
                ],
                pager: "#customerGridPager",
                 postData: {
                        query: function() { return $("#search-name").val(); },
                        customerType: function() { return $("#search-customerType").val(); }

                    } ,
                    toolbarfilter: true,
                rowNum: 10,
                rowList: [10, 20, 30],
                sortname: "customerId",
                sortorder: "desc",
                viewrecords: true,
                gridview: true,
                autoencode: true,
                caption: "Customers" ,
                height:400,
                autowidth : true,
                jsonReader : {root:"customers"},
                gridComplete: function(){
			        var ids = jQuery("#customerGrid").jqGrid('getDataIDs');
//                    for(var i=0;i < ids.length;i++){
//                        var cl = ids[i];
//                        be = "<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"jQuery('#customerGrid').editRow('"+cl+"');\"><i class='fa fa-pencil'></i></button>";
//                        se = "<button class='btn btn-xs btn-default btn-quick' title='Save Row' onclick=\"jQuery('#customerGrid').saveRow('"+cl+"');\"><i class='fa fa-save'></i></button>";
//                        ca = "<button class='btn btn-xs btn-default btn-quick' title='Cancel' onclick=\"jQuery('#customerGrid').restoreRow('"+cl+"');\"><i class='fa fa-times'></i></button>";
//                        jQuery("#customerGrid").jqGrid('setRowData',ids[i],{ act: be+se+ca });
//                    }
                }

                });

                  jQuery("#productGrid").jqGrid('navGrid', "#productGridPager", {
                    		edit : false,
                    		add : false,
                    		del : true
                    	});

                jQuery("a.get_selected_ids").bind("click", function() {
                		s = jQuery("#productGrid").jqGrid('getGridParam', 'selarrrow');

                	});


            $( "#create-product").button().click(function () {


             		var options = {
                            url:       'save' ,
                            type:      'post' ,
                            dataType:  'json' ,
                            clearForm: true  ,
                            resetForm: true  ,
                            timeout:   9000  ,
                            beforeSubmit: validate,
                            success:    function() {
                               grid.trigger("reloadGrid");

                                $('#customerForm').modal('hide')
                             }  ,
                              error:    function() {
                               alert('Error');
                             }
                        };

						$("#new-customer-form").ajaxSubmit(options) ;

			});
			 $( "#search-customer-btn").button().click(function () {

             	grid.trigger("reloadGrid");
			});

			$('#customerForm').modal({
                    keyboard: false ,
                    backdrop: false,
                    show: false
            })

             function actionFormat( cellvalue, options, rowObject ){
                          	return "<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"showDetails('"+cellvalue+"');\"><i class='fa fa-pencil'></i></button>"+
                          	"<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"showTransactionDetails('"+cellvalue+"');\"><i class='fa fa-list'></i></button>";

                        }
                        function actionUnFormat( cellvalue, options, cell){
                        	return $('img', cell).attr('src');
                        }
                         customerTransactionGrid=  $("#customerTransactionGrid").jqGrid({
                                        url: "transactionHistory",
                                        datatype: "json",
                                        mtype: "GET",
                                        colNames: ["CUSTOMER","TYPE", "NUM", "DATE","AMOUNT"],
                                        colModel: [

                                            { name: "customerName" ,align: "left" },
                                            { name: "transactionType" ,align: "left" },
                                            { name: "transactionId" ,align: "left"},
                                            { name: "transactionDate", align: "left" },
                                            { name: "transactionAmount", align: "left" ,summaryTpl: "TOTAL: {0}",summaryType: "sum",formatter:'currency' ,formatoptions:currencyformatoptions },

                                        ],
                                        pager: "#customerTransactionGridPager",
                                         postData: {
                                                transactionType: function() { return $("#search-transaction-type").val(); },
                                                dateRange: function() { return $("#search-transaction-dateRange").val(); },
                                                customerId: function() { return $("#trx-customerId").val(); }

                                            } ,
                                            footerrow : true,
                                            userDataOnFooter : true,
                                            toolbarfilter: true,
                                        rowNum: 10,
                                        rowList: [10, 20, 30],
                                        sortname: "transactionDate",
                                        sortorder: "desc",
                                        viewrecords: true,
                                        gridview: true,
                                        autoencode: true,
                                        caption: "Transactions" ,
                                        height:400,
                                        autowidth : true,
                                        jsonReader: {
                                                root: 'transactions',
                                               userdata: function (obj) {
                                                    return {
                                                        transactionAmount: obj.totalTransactionAmount
                                                    };
                                                }
                                            },
                                        gridComplete: function(){
                        			        var ids = jQuery("#customerGrid").jqGrid('getDataIDs');

                                        }

                                        });




                 $("#search-transaction-type , #search-transaction-dateRange").on('change', function() {
                      customerTransactionGrid.trigger("reloadGrid")
                });


                $( "#search-customer" ).autocomplete({

                            source: function( request, response ) {
                            $.ajax({
                                      url: "../customer/search",
                                      dataType: "json",
                                      data: {
                                           query: request.term
                                            },
                                      success: function( data ) {
                                         response($.map(data.customers, function(item) {
                                                      return {
                                                      label: item.name+', '+item.address.city,
                                                      value: item.customerId,
                                                      customer:item,
                                                              }
                                                  }));
                                           }
                                        }); },
                                          minLength: 2,
                                                     select: function( event, ui ) {

                                                                        var customerInfo = ui.item.customer;
                                                                        $( "#customerId" ).val(customerInfo.customerId);
                                                                        $( "#customer-company" ).html(customerInfo.companyName);
                                                                        $( "#customer-name" ).html(customerInfo.name);
                                                                        $( "#customer-city" ).html(customerInfo.address.city);
                                                                        $( "#customer-mobile" ).html(customerInfo.mobileNumber);
                                                                        $( "#customerinfo" ).hide();
                                                                         $( "#customerDetail" ).removeClass("hide");
                                                                        $(this).val("");
                                                                        return true;
                                                            }
                                                            });

                                                          $( "#search-customer" ).autocomplete("option", "appendTo", "#customerinfo" );


              	                 $( "#customerDetailButton").button().click(function () {
                           	         $( "#customerinfo" ).show();
                                     $( "#customerDetail" ).addClass("hide");
              			        });

                                    function enableCustomerSearch(){
                                         $( "#customerinfo" ).show();
                                         $( "#customerDetail" ).addClass("hide");
                                    }




                        $('button.modelWindow').on('shown.bs.modal', function () {
                                 e.preventDefault();
                                 var title = $(this).data('title');
                                 $("#customer-payment-model-title").html(title);
                        });




                  $( "#create-payment-close").button().click(function () {


                                    var options = {
                                             url:       'savePayment' ,
                                             type:      'post' ,
                                             dataType:  'json' ,
                                             clearForm: true  ,
                                             resetForm: true  ,
                                             timeout:   9000  ,
                                             beforeSubmit: validate,
                                             success:    function() {
                                                 $('#paymentForm').modal('hide')
                                              }  ,
                                             error:    function() {
                                                 $('input.currency').formatCurrency();
                                                 alert('Error');
                                              },
                                              beforeSend: function() {

                                              }
                                         };


                                       $("#payment-form").ajaxSubmit(options) ;

                            });



    });




  function showTransactionDetails(index){


            $.ajax({url: "getDetails",
                dataType: "json",
                data: {
                        "customerId": index
                      },success: function(customerObj){
                            myApp.hidePleaseWait();
                            if(customerObj.customerId)
                               {
                                       loadFormData(customerObj,'customerTransaction');
                                        $('#customerTransaction > #model-title').text("Customer Information");
                                        $("#trx-customerId").val(index);
                                        customerTransactionGrid.jqGrid('setGridParam',{datatype: 'json'});
                                        customerTransactionGrid.trigger("reloadGrid");
                                        var options= {'keyboard':false,'show':true};
                                        $('#customerTransaction').modal(options);

                                }
                              else{

                                  }
                     }
               });


          }
         function showDetails(index){
                     myApp.showPleaseWait();
                         $.ajax({url: "getDetails", dataType: "json",data: {
                                           "customerId": index
                                 },success: function(productObj){
                                    myApp.hidePleaseWait();
                                   if(productObj.customerId)
                                   {
                                          loadFormData(productObj,'customerForm');
                                          $('#model-title').text("Edit Customer");
                                          var options= {'keyboard':false,'show':true};
                                          $('#customerForm').modal(options);
                                   }
                                    else{

                                    }

                               }});

          }



